package com.fanghaoran.notes.util;

import java.util.ArrayList;
import java.util.Random;

/**
 * @Author: win11
 * @Date: 2023/03/17/14:10
 * @Description: 生成验证码
 */
public class CodeUtil {

    public static String getCode(){

        //1.创建一个集合
        //52  索引的范围：0 ~ 51
        ArrayList<Character> list = new ArrayList<>();
        //2.添加字母 a - z  A - Z
        for (int i = 0; i < 26; i++) {
            //a - z
            list.add((char)('a' + i));
            //A - Z
            list.add((char)('A' + i));
        }
        //4.生成4个随机字母
        StringBuilder sb=new StringBuilder();

        Random r = new Random();
        for (int i = 0; i < 4; i++) {
            //获取随机索引
            int randomIndex = r.nextInt(list.size());
            char c = list.get(randomIndex);
            sb.append(c);
        }
        String result = sb.toString();
        //5.在后面拼接数字 0~9
        int number = r.nextInt(10);
        //6.把随机数字拼接到result的后面
        result = result + number;
        //7.把字符串变成字符数组
        char[] chars = result.toCharArray();
        //8.在字符数组中生成一个随机索引
        int index = r.nextInt(chars.length);
        //9.拿着4索引上的数字，跟随机索引上的数字进行交换
        char temp = chars[4];
        chars[4] = chars[index];
        chars[index] = temp;
        //10.把字符数组再变回字符串 然后返回
        return new String(chars);
    }

    /**
     * 生成指定长度的随机邀请码
     * @return 随机邀请码字符串
     */
    public static String generateInviteCode() {
        StringBuilder codeBuilder = new StringBuilder();
        int charCount = Constants.CHARS.length();

        // 随机选取字符集中的字符组成邀请码
        Random r = new Random();
        for (int i = 0; i < Constants.CODE_LENGTH; i++) {
            int index = r.nextInt(charCount);
            codeBuilder.append(Constants.CHARS.charAt(index));
        }

        return codeBuilder.toString();
    }
}
